import datetime
import json

import requests
from PyQt5.QtCore import QUrl, Qt, QProcess
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QAbstractItemView, QMessageBox
from pollingthread import PollingThread
from peopleSelect import PeopleSelect


# Qt 心理新联后端实现代码
class Psychology(PeopleSelect):
    def __init__(self, mainWindow):
        super().__init__(mainWindow.ui.psychology, mainWindow)
        self.process = QProcess()

        # 主界面槽连接信号
        self.ui.btn_start.clicked.connect(self.start_training)
        self.ui.btn_shop.clicked.connect(self.start_shop)
        self.ui.btn_monitor.clicked.connect(self.monitor)

    def loadData(self):
        super().loadData()

        # 获取正在参训的人员信息
        self.userListModel = QStandardItemModel(0, 5)
        self.userListModel.setHorizontalHeaderLabels(
            ['警员名称', '警员编号', '训练日期', '开始时间', '结束时间', '体验内容'])
        self.ui.view_userList.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 设置表格不可编辑
        self.ui.view_userList.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置表格只可整行选择
        self.ui.view_userList.verticalHeader().hide()
        self.ui.view_userList.setModel(self.userListModel)
        response = self.session.get(self.mainWindow.url + '/admin/traindata/data')
        text = json.loads(response.text)
        dataList = text['data']
        count = 0
        for data in dataList:
            item_name = QStandardItem(str(data['Name']))
            item_number = QStandardItem(str(data['number']))
            item_date = QStandardItem(str(data['date']))
            item_stime = QStandardItem(str(data['stime']))
            item_etime = QStandardItem(str(data['etime']))
            item_train = QStandardItem(str(data['train']))
            self.userListModel.setItem(count, 0, item_name)
            self.userListModel.setItem(count, 1, item_number)
            self.userListModel.setItem(count, 2, item_date)
            self.userListModel.setItem(count, 3, item_stime)
            self.userListModel.setItem(count, 4, item_etime)
            self.userListModel.setItem(count, 5, item_train)
            count = count + 1

    # 提交新建的情景
    def start_training(self):
        # 判断是否选择参训人员
        if not self.checkSelected():
            ERROR("请选择参训人员")
            return

        ids = self.getSelectedIds()
        # 判断是否多选人员
        if len(ids) > 1:
            ERROR('仅支持单人训练')
            return
        names = self.getSelectedNames()
        body = {
            "code": ids[0],
            "name": names[0]
        }
        response = requests.post(url=self.mainWindow.psychology_web_url + '/operate/api/v1/adduser', json=body)
        try:
            data = json.loads(response.text)
            user_id = data['userid']
            print(data)
        except:
            ERROR(message='情景体验系统连接失败')
            return

        start_time = datetime.datetime.now()
        body = {
            "userid": user_id,
            "iswrite": True
        }
        response = requests.post(url=self.mainWindow.psychology_control_url + '/v1/writehrv', json=body)
        try:
            json.loads(response.text)
            print(response)
        except:
            ERROR(message='情景体验系统开始训练失败')
            return
        response = requests.get(url=self.mainWindow.url + '/admin/police/getOne/' + ids[0])
        data = json.loads(response.text)['data']
        print(data)
        police = data['police']
        body = {
            "user_id": police['id'],
            "user_code": police['code'],
            "user_name": police['name'],
            "user_status": "正在训练",
            "time": start_time.strftime("%Y-%m-%d %H:%M:%S")
        }
        requests.post(url=self.mainWindow.url + '/admin/psych_realtime/start_training', json=body)
        self.process.setWorkingDirectory(
            self.mainWindow.psychology_program_path[:self.mainWindow.psychology_program_path.rfind('\\') + 1])
        # 启动外部程序，参数是一个列表
        self.process.start(self.mainWindow.psychology_program_path)
        thread = PollingThread(user_id=user_id,
                               name="polling",
                               url=self.mainWindow.psychology_web_url,
                               control_url=self.mainWindow.psychology_control_url,
                               socket_url=self.mainWindow.psychology_socket_url,
                               ue_url=self.mainWindow.psychology_ue_url)
        thread.start()
        # 传入-1代表无限期等待子窗口完成任务
        self.process.waitForFinished(-1)
        thread.stop()
        end_time = datetime.datetime.now()
        body = {
            "userid": user_id,
            "iswrite": False
        }
        response = requests.post(url=self.mainWindow.psychology_control_url + '/v1/writehrv', json=body)
        body = {
            "userid": user_id,
            "starttime": start_time.strftime("%Y-%m-%d %H:%M:%S"),
            "endtime": end_time.strftime("%Y-%m-%d %H:%M:%S")
        }
        response = requests.post(url=self.mainWindow.psychology_web_url + '/operate/api/v1/experiencetime', json=body)
        requests.get(url=self.mainWindow.url + '/admin/psych_realtime/end_training/' + str(police['id']))
        return

    def start_shop(self):
        self.process.setWorkingDirectory(
            self.mainWindow.psychology_shop_path[:self.mainWindow.psychology_shop_path.rfind('\\') + 1])
        # 启动外部程序，参数是一个列表
        self.process.start(self.mainWindow.psychology_shop_path, [])
        self.process.waitForFinished()

    def monitor(self):
        self.mainWindow.ui.stackedWidget.setCurrentWidget(self.mainWindow.ui.web.page_widgets)
        self.mainWindow.ui.web.browser.load(QUrl(self.mainWindow.url + '/admin/score/'))


def ERROR(message):
    msg_box = QMessageBox(QMessageBox.Critical, '错误', message)
    msg_box.exec_()
